package com.example.yang_app_sixth_server2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Iterator;

class ServerProcessThread implements Runnable{
    Socket sk=null;
    BufferedReader br=null;
    Handler handler=null;
    public ServerProcessThread(Socket sk, Handler handler) throws IOException {
        this.sk=sk;
        this.handler=handler;
        br=new BufferedReader(new InputStreamReader(sk.getInputStream(),"utf-8"));
    }

    @Override
    public void run() {
        String content=null;
        while((content=readFromClient())!=null){
            Message msg=new Message();
            msg.what=0x1234;
            Bundle bundle=new Bundle();
            bundle.putString("new_content",content);
            msg.setData(bundle);
            handler.sendMessage(msg);
            for(Iterator<Socket> it = ServerListener.socketList.iterator(); it.hasNext();){
                Socket outSk=it.next();
                try{
                    OutputStream os=outSk.getOutputStream();
                    os.write((content+"\n").getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                    it.remove();
                }
            }
        }


    }
    private String readFromClient(){
        try{
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            ServerListener.socketList.remove(sk);
        }
        return null;
    }
}
